var Viewer = function() {

  var index = 0;
  var images = [];
  var domElement = document.querySelector('.viewer');

  function init(fileData, callback) {
    var ua = new bitjs.archive['Unrarrer'](fileData, 'lib/bitjs/');
    ua.addEventListener(bitjs.archive.UnarchiveEvent.Type.EXTRACT, function (e) {
      var blob = new Blob([e.unarchivedFile.fileData], { type: 'image/jpg' });
      images.push({
        name: e.unarchivedFile.filename,
        url: window.URL.createObjectURL(blob)
      });
      if (images.length === 1) {
        chrome.app.window.current().show();
        chrome.app.window.current().fullscreen();
        show();
        callback(blob);
      }
    });
    ua.start();
  }

  function show() {
    domElement.animate([{ opacity: '1' }, { opacity: '.2' }], 200);
    setTimeout(function() {
      domElement.style.backgroundImage = 'url('+ images[index].url+')';
      window.document.title = images[index].name;
    }, 200);
  }

  function showNext() {
    if (index >= images.length)
      return;
    index++
    show();
  }

  function showPrevious() {
    if (index === 0)
      return
    index--;
    show();
  }

  return {
    init: init,
    showNext: showNext,
    showPrevious: showPrevious,
  }
};

document.body.addEventListener('click', function(event) {
  if (event.pageX > screen.availWidth / 2)
    viewer.showNext();
  else
    viewer.showPrevious();
});

document.body.addEventListener('keydown', function(event) {
  switch (event.keyCode) {
    case 37: // up arrow
    case 38: // left arrow
    case 75: // k
      viewer.showPrevious(); break;
    case 39: // right arrow
    case 40: // down arrow
    case 74: // j
      viewer.showNext(); break;
  };
});


function setupContextMenus() {
  // Remove all context menus first.
  chrome.contextMenus.removeAll(function() {
    // Recreate just the ones we want.
    chrome.contextMenus.create({
      title: 'Toggle fullscreen',
      id: 'toggleFullscreen'
    });

    function onContextMenuClick(itemData) {
      if (document.hasFocus()) {
        var appWindow = chrome.app.window.current();
        if (appWindow.isFullscreen())
          chrome.app.window.current().restore();
        else
          chrome.app.window.current().fullscreen();
      }
    };

    chrome.contextMenus.onClicked.addListener(onContextMenuClick);
  });
};

window.addEventListener('focus', setupContextMenus);


var viewer = Viewer();